package com.iu.dao;

import com.iu.bean.UserBean;
import com.iu.uitl.DBUtil;

import java.sql.*;

public class UserDao {
    Connection connection;
    // Statement statement;

    /*备忘录用户注册*/
    public boolean userRegister(UserBean userBean) {
        connection = DBUtil.getConnection();
        if (userBean.getPass().isEmpty() && userBean.getTel().isEmpty()) {
            return false;
        }
        try {

            PreparedStatement preparedStatement = connection.prepareStatement("insert into note_user(name,pass,tel,qq,wechat) values(?,?,?,?,?)");
//            statement = connection.createStatement();
//            statement.execute();
            preparedStatement.setString(1, userBean.getName());
            preparedStatement.setString(2, userBean.getPass());
            preparedStatement.setString(3, userBean.getTel());
            preparedStatement.setString(4, userBean.getQq());
            preparedStatement.setString(5, userBean.getWechat());
            preparedStatement.execute();
            DBUtil.closeResources(connection, preparedStatement, null);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

    }

    /*用户登录接口实现*/
    public boolean userLogin(String tel, String pass) {
        String DBpass;
        PreparedStatement preparedStatement = null;
        connection = DBUtil.getConnection();
        try {
            preparedStatement = connection.prepareStatement("select pass from note_user where tel=?");
            preparedStatement.setString(1, tel);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
//                resultSet.first()
                DBpass = resultSet.getString("pass");//?待验证? 已验证 初始值为1 特别注意：用字符串取值要加双引号！
                if (pass.equals(DBpass)) {
                    return true;
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResources(connection, preparedStatement, null);//为何此处不用关闭resultSet，而且写入报错？
        }
        return false;
    }

    /*根据电话号码查找id*/
    public int getIdByTel(String tel) {
        int id = -1;
        PreparedStatement preparedStatement = null;
        connection = DBUtil.getConnection();
        try {
            preparedStatement = connection.prepareStatement("select id from note_user where tel=?");
            preparedStatement.setString(1, tel);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                id = resultSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResources(connection, preparedStatement, null);
        }
        return id;
    }

}

